package cn.com.homeyoda.aimate.aihealth.ui;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.AVATAR;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.LOGIN_SUCCESS;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.LOGOUT_SUCCESS;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.NAME;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;

import com.jeremyliao.liveeventbus.LiveEventBus;
import com.wzq.mvvmsmart.utils.GlideLoadUtils;
import com.wzq.mvvmsmart.utils.SPUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityMainBinding;
import cn.com.homeyoda.aimate.aihealth.ui.health_manage.HealthManageFragment;
import cn.com.homeyoda.aimate.aihealth.ui.health_qa.HealthQaListFragment;
import cn.com.homeyoda.aimate.aihealth.ui.message.MessageFragment;
import cn.com.homeyoda.aimate.aihealth.ui.my.MyActivity;
import cn.com.homeyoda.aimate.aihealth.ui.videoinspect.VideoInspectFragment;
import cn.com.homeyoda.aimate.aihealth.ui.zixun.ZiXunFragment;
import cn.com.homeyoda.aimate.aihealth.views.NavigationButton;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel> implements View.OnClickListener {

    private NavigationButton mCurrentNavButton;
    private FragmentManager mFragmentManager;
    public static MainActivity mainActivity;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_main;
    }

    @Override
    public int initVariableId() {
        return 0;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initBottomBar();
        mainActivity = this;
    }

    private void initBottomBar() {
        mFragmentManager = getSupportFragmentManager();
        binding.mainContent.navItemAitj.init(R.drawable.ic_main_aiti, R.string.tab_aitj, VideoInspectFragment.class);
        binding.mainContent.navItemXx.init(R.drawable.ic_main_xx, R.string.tab_xx, MessageFragment.class);
        binding.mainContent.navItemJkwd.init(R.drawable.ic_main_jkwk, R.string.tab_jkwd, HealthQaListFragment.class);
        binding.mainContent.navItemJkgl.init(R.drawable.ic_main_jkgl, R.string.tab_jkgl, HealthManageFragment.class);
        binding.mainContent.navItemZxzx.init(R.drawable.ic_main_zxzx, R.string.tab_zxzx, ZiXunFragment.class);

        binding.mainContent.navItemAitj.setOnClickListener(this);
        binding.mainContent.navItemXx.setOnClickListener(this);
        binding.mainContent.navItemJkwd.setOnClickListener(this);
        binding.mainContent.navItemJkgl.setOnClickListener(this);
        binding.mainContent.navItemZxzx.setOnClickListener(this);
        binding.mainContent.navItemUser.setOnClickListener(this);
        setItemUserVisibility(isLogin());
        doSelect(binding.mainContent.navItemAitj);
    }

    private void setItemUserVisibility(boolean isLogin) {
        binding.mainContent.navItemUser.setVisibility(isLogin ? VISIBLE : GONE);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id != R.id.nav_item_aitj && !isLogin()) {
            startLoginActivity();
            return;
        }
        if (id == R.id.nav_item_aitj) {
            doSelect(binding.mainContent.navItemAitj);
        } else if (id == R.id.nav_item_xx) {
            doSelect(binding.mainContent.navItemXx);
        } else if (id == R.id.nav_item_jkwd) {
            doSelect(binding.mainContent.navItemJkwd);
        } else if (id == R.id.nav_item_jkgl) {
            doSelect(binding.mainContent.navItemJkgl);
        } else if (id == R.id.nav_item_zxzx) {
            doSelect(binding.mainContent.navItemZxzx);
        } else if (id == R.id.nav_item_user) {
            startActivity(new Intent(this, MyActivity.class));
        }
    }

    private void doSelect(NavigationButton newNavButton) {

        NavigationButton oldNavButton = null;
        if (mCurrentNavButton != null) {
            oldNavButton = mCurrentNavButton;
            if (oldNavButton == newNavButton) {
                onReselect(oldNavButton);
                return;
            }
            oldNavButton.setSelected(false);
        }
        newNavButton.setSelected(true);
        doTabChanged(oldNavButton, newNavButton);
        mCurrentNavButton = newNavButton;
    }

    private void doTabChanged(NavigationButton oldNavButton, NavigationButton newNavButton) {
        FragmentTransaction ft = mFragmentManager.beginTransaction();
        if (oldNavButton != null) {
            if (oldNavButton.getFragment() != null) {
                ft.detach(oldNavButton.getFragment());
            }
        }
        if (newNavButton != null) {
            Fragment fragment = Fragment.instantiate(this,
                    newNavButton.getClx().getName(), null);
            setFragment(fragment);
        }
        ft.commit();
    }

    public void setFragment(Fragment fragment) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.flContainer, fragment)
                .commit();
    }

    public void onReselect(NavigationButton navigationButton) {
        Fragment fragment = navigationButton.getFragment();
        if (fragment != null) {
            fragment.onResume();// 是否要重新刷新？
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getSupportFragmentManager().getFragments();
        if (!getSupportFragmentManager().getFragments().isEmpty()) {
            List<Fragment> fragments = getSupportFragmentManager().getFragments();
            for (Fragment mFragment : fragments) {
                mFragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    @SuppressLint("CheckResult")
    @Override
    public void initViewObservable() {
        super.initViewObservable();

        LiveEventBus.get(LOGIN_SUCCESS, String.class).observe(this, aBoolean ->{
                    setItemUserVisibility(true);
                    viewModel.queryFaceInfo();
                });


        LiveEventBus.get(LOGOUT_SUCCESS, Boolean.class).observe(this, aBoolean -> {
            setItemUserVisibility(false);
            SPUtils.getInstance().remove(AVATAR);
            SPUtils.getInstance().remove(NAME);
            Observable.just(binding.mainContent.navItemAitj)
                    .delay(200, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(navItem -> doSelect(navItem), Throwable::printStackTrace);
        });

        viewModel.faceInfoData.observe(this, faceInfoBean -> {
            if (faceInfoBean != null) {
                String avatar = faceInfoBean.getAvatar();
                String name = faceInfoBean.getName();
                GlideLoadUtils.loadImg(binding.mainContent.ivUserIcon, avatar, R.mipmap.ic_member1);
                binding.mainContent.tvUserName.setText(name);

                String saveAvatar = SPUtils.getInstance().getString(AVATAR);
                String saveName = SPUtils.getInstance().getString(NAME);
                if (!TextUtils.equals(saveAvatar, avatar)) {
                    SPUtils.getInstance().put(AVATAR, avatar);
                }
                if (!TextUtils.equals(saveName, name)) {
                    SPUtils.getInstance().put(NAME, name);
                }
            }
        });

    }

    @Override
    public MainViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(MainViewModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.queryFaceInfo();
    }

}
